<template>
    <div class="work-order">
        <div class="header">
            <div class="info">
                <span>创建人：赵六</span>
                <span>创建时间：2025-12-08 23:37:12</span>
                <span>最后修改人：赵六</span>
                <span>最后修改时间：2022-06-07 19:49:12</span>
            </div>
            <div class="actions">
                <ElButton size="small">编辑</ElButton>
                <ElButton size="small">删除</ElButton>
                <ElButton size="small">打印</ElButton>
                <ElButton size="small" type="primary">上线</ElButton>
                <ElButton size="small">关闭</ElButton>
            </div>
        </div>

        <ElTabs>
            <ElTabPane label="工单详情">
                <div class="section base-info">
                    <h3>基础信息</h3>
                    <div class="row">
                        <div class="col">
                            <p>工单编号：{{ baseInfo.productionworkorderId }}</p>
                            <p>单据时间：{{ baseInfo.productionworkorderDate }}</p>
                            <p>销售订单：{{ baseInfo.productionworkorderDId || '无' }}</p>
                            <p>负责人：{{ baseInfo.productionworkorderStatus }}</p>
                            <p>备注：{{ baseInfo.productionworkorderDescription }}</p>
                        </div>
                        <div class="col">
                            <p>工单名称：{{ baseInfo.productionworkorderName }}</p>
                            <p>关联生产单号：{{ baseInfo.productionworkorderHId }}</p>
                            <p>关联项目：{{ baseInfo.productionworkorderTypeName }}</p>
                            <p>所属部门：{{ baseInfo.productionworkorderWId }}</p>
                        </div>
                    </div>
                </div>

                <!-- 生产物品部分 -->
                <div class="section product-info">
                    <h3>生产物品</h3>
                    <div class="row">
                        <div class="col">
                            <p>产品名称：{{ productInfo.productionworkorderTitle }}</p>
                            <p>规格型号：{{ productInfo.productionworkorderType }}</p>
                            <p>物品类别：{{ productInfo.productionworkorderGender }}</p>
                            <p>计划产量：{{ productInfo.productionworkorderNumber }}</p>
                            <p>计划结束时间：{{ productInfo.productionworkorderJDorker }}</p>
                        </div>
                        <div class="col">
                            <p>产品编号：{{ baseInfo.productionworkorderNameId }}</p>
                            <p>单位：{{ productInfo.productionworkorderHand }}</p>
                            <p>物品分类：{{ productInfo.productionworkorderDorker }}</p>
                            <p>计划开始时间：{{ productInfo.productionworkorderNDorker }}</p>
                            <p>实际开始时间：{{ baseInfo.productionworkorderDate }}</p> <!-- 假设实际开始时间暂时用单据时间，需根据实际接口调整 -->
                        </div>
                    </div>
                </div>

                <div class="section process">
                    <h3>工序流程</h3>
                    <ElButton size="small" @click="exportProcess">导出</ElButton>
                    <ElTable :data="processList" border style="width: 100%">
                        <ElTableColumn type="index" label="序号" width="50"></ElTableColumn>
                        <ElTableColumn label="工序编码" prop="processflowId"></ElTableColumn>
                        <ElTableColumn label="工序名称" prop="processflowName"></ElTableColumn>
                        <ElTableColumn label="加工顺序" prop="processflowType"></ElTableColumn>
                        <ElTableColumn label="工艺规程" prop="processflowDescription"></ElTableColumn>
                        <ElTableColumn label="状态" prop="processflowTypeState"></ElTableColumn>
                        <ElTableColumn label="负责人" prop="processflowStatus"></ElTableColumn>
                        <ElTableColumn label="所在部门" prop="processflowStatusDescription"></ElTableColumn>
                        <ElTableColumn label="计划开始时间" prop="processflowTypeDescription"></ElTableColumn>
                        <ElTableColumn label="实际开始时间" prop="processflowTypeDescription"></ElTableColumn>
                        <ElTableColumn label="计划结束时间" prop="processflowTypeJDescription"></ElTableColumn>
                        <ElTableColumn label="实际结束时间" prop="processflowTypeJDescription"></ElTableColumn>
                        <ElTableColumn label="计划产量" prop="processflowTypeDescrnTIme"></ElTableColumn>
                        <ElTableColumn label="完工数量" prop="processflowTypeNumber"></ElTableColumn>
                        <ElTableColumn label="合格数量" prop="processflowTypeNumberDescription"></ElTableColumn>
                        <ElTableColumn label="合格率" width="80">
                            <template #default="scope">
                                <span v-if="scope.row.processflowTypeNumber > 0">
                                    {{ (scope.row.processflowTypeNumberDescription / scope.row.processflowTypeNumber *
                                        100).toFixed(2) }}%
                                </span>
                                <span v-else>0%</span>
                            </template>
                        </ElTableColumn>
                        <ElTableColumn label="操作" prop="action">
                            <template #default="{ row }">
                                <span @click="handleReport(row)" class="action-link">报工</span>
                                <span class="action-divider">|</span>
                                <span @click="handleCloseProcess(row)" class="action-link">关闭</span>
                            </template>
                        </ElTableColumn>
                    </ElTable>
                </div>

                <div class="section attachments">
                    <h3>附件</h3>
                    <div class="attachment-list">
                        <div v-for="(item, index) in attachments" :key="index" class="attachment-item">
                            <p>新建文本文档PDF</p>
                            <p>文件大小：0 Bytes</p>
                            <p>上传日期：2022-08-11 17:45:27</p>
                            <ElButton size="small">查看</ElButton>
                            <ElButton size="small">下载</ElButton>
                        </div>
                    </div>
                </div>
            </ElTabPane>
        </ElTabs>

        <!-- 报工对话框 -->
        <ElDialog title="报工" v-model="isReportDialogVisible" width="800px" :before-close="handleReportClose">
            <div class="report-form">
                <div class="form-header">
                    <div class="form-row">
                        <div class="form-col">
                            <span class="form-label">工序编号：</span>
                            <span class="form-value">{{ currentProcess.code }}</span>
                        </div>
                        <div class="form-col">
                            <span class="form-label">工序名称：</span>
                            <span class="form-value">{{ currentProcess.name }}</span>
                        </div>
                    </div>
                    <div class="form-row">
                        <div class="form-col">
                            <span class="form-label">负责人：</span>
                            <span class="form-value">{{ currentProcess.responsible }}</span>
                        </div>
                        <div class="form-col">
                            <span class="form-label">部门：</span>
                            <span class="form-value">{{ currentProcess.department }}</span>
                        </div>
                    </div>
                </div>

                <div class="form-actions">
                    <ElButton type="primary" size="small" @click="addReportItem">添加</ElButton>
                    <ElButton type="danger" size="small" @click="removeSelectedItems">
                        移除
                    </ElButton>
                </div>

                <ElTable :data="reportItems" border stripe height="300" @selection-change="handleSelectionChange">
                    <ElTableColumn type="selection" width="55"></ElTableColumn>
                    <ElTableColumn type="index" label="序号" width="50"></ElTableColumn>
                    <ElTableColumn label="生产部门" prop="department">
                        <template #default="scope">
                            <ElSelect v-model="scope.row.department" placeholder="选择部门" size="small">
                                <ElOption v-for="dept in departmentOptions" :key="dept.value" :label="dept.label"
                                    :value="dept.value"></ElOption>
                            </ElSelect>
                        </template>
                    </ElTableColumn>
                    <ElTableColumn label="生产人员" prop="people">
                        <template #default="scope">
                            <ElSelect v-model="scope.row.people" placeholder="选择人员" size="small">
                                <ElOption v-for="person in peopleOptions" :key="person.value" :label="person.label"
                                    :value="person.value"></ElOption>
                            </ElSelect>
                        </template>
                    </ElTableColumn>
                    <ElTableColumn label="报工数量" prop="quantity">
                        <template #default="scope">
                            <ElInput v-model.number="scope.row.quantity" type="number" size="small" min="0"
                                @change="updateUnqualified(scope.row)"></ElInput>
                        </template>
                    </ElTableColumn>
                </ElTable>
            </div>

            <template #footer>
                <ElButton @click="isReportDialogVisible = false">取消</ElButton>
                <ElButton type="primary" @click="submitReport">确定</ElButton>
            </template>
        </ElDialog>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import {
    ElButton,
    ElTable,
    ElTableColumn,
    ElDialog,
    ElInput,
    ElSelect,
    ElOption,
    ElTabs,
    ElTabPane,
    ElMessageBox,
    ElMessage
} from 'element-plus';
import axios from 'axios';
import { useRouter, useRoute } from 'vue-router';
const router = useRouter();
const route = useRoute();
var id = route.query.id
// 对话框状态
const isReportDialogVisible = ref(false);
const currentProcess = ref({
    code: '',
    name: '',
    responsible: '',
    department: ''
});
const reportItems = ref([
    { department: '', people: '', quantity: 0, qualified: 0, unqualified: 0, remark: '' }
]);
const multipleSelection = ref([]);

// 表格数据
const processList = ref([]);
const attachments = ref([
    { name: '新建文本文档PDF', size: '0 Bytes', date: '2022-08-11 17:45:27' }
]);

// 下拉选项
const departmentOptions = ref([
    { value: '销售部', label: '销售部' },
    { value: '人事部', label: '人事部' },
    { value: '财务部', label: '财务部' },
    { value: '车间部', label: '车间部' },
    { value: '开发部', label: '开发部' }
]);

const peopleOptions = ref([
    { value: '张三', label: '张三' },
    { value: '李四', label: '李四' },
    { value: '王五', label: '王五' },
    { value: '赵六', label: '赵六' },
    { value: '钱七', label: '钱七' }
]);

// 报工处理
const handleReport = (row) => {
    currentProcess.value = {
        // 原有字段
        code: row.processflowId,
        name: row.processflowName,
        responsible: row.processflowStatus,
        department: row.processflowStatusDescription,
        processflowType: row.processflowType,
        processflowDescription: row.processflowDescription,
        processflowTypeDescription: row.processflowTypeDescription,
        processflowTypeJDescription: row.processflowTypeJDescription,
        processflowTypeDescrnTIme: row.processflowTypeDescrnTIme.toString(), // 计划产量转为字符串
        // 新增后端需要的字段（从表格行获取）
        processflowTypeState: row.processflowTypeState, // 状态（表格列存在）
        processflowTypeAddres: '', // 若无该数据，留空
    };
    isReportDialogVisible.value = true;
};

// 提交报工
const submitReport = () => {
    // 数据校验
    if (reportItems.value.length === 0) {
        ElMessage.warning('请添加报工项目');
        return;
    }

    const invalidItems = reportItems.value.filter(
        item => !item.department || !item.people || item.quantity <= 0
    );

    if (invalidItems.length > 0) {
        ElMessage.warning('请完善所有报工项目的部门、人员和数量信息');
        return;
    }

    // 计算总数量并转为字符串
    const totalQuantity = reportItems.value.reduce((sum, item) => sum + item.quantity, 0).toString();
    // 报工明细数组（按后端要求格式处理）
    const reportDetails = reportItems.value.map(item => ({
        qualified: item.qualified.toString(), // 合格数量转字符串（若有）
    }));
    const fromsw = {
        // "processflowId": "",//工序编码
        // "processflowName": "",//工序名称
        // "processflowType": "",//加工顺序
        // "processflowDescription": "",//工艺流程
        // "processflowStatus": "",//负责人
        // "processflowStatusDescription": "",//所在部门
        // "processflowTypeDescription": "",//计划开始时间
        // "processflowTypeJDescription": "",//计划结束时间
        // "processflowTypeDescrnTIme": "",//计划产量
        // "processflowTypeAddres": "",//备注
        // "processflowTypeState": "",//状态
        // "processflowTypeNumber": "",//完工数量
        // "processflowTypeNumberDescription": "",//合格数量
        // "processflowTypeBumian": "",//部门
        // "personnel": "",//人员
        // "personnelDescription": "",//报工数量



        processflowId: currentProcess.value.code,
        processflowName: currentProcess.value.name,
        processflowType: currentProcess.value.processflowType,
        processflowDescription: currentProcess.value.processflowDescription,
        processflowStatus: currentProcess.value.responsible,
        processflowStatusDescription: currentProcess.value.department,
        processflowTypeDescription: currentProcess.value.processflowTypeDescription,
        processflowTypeJDescription: currentProcess.value.processflowTypeJDescription,
        processflowTypeDescrnTIme: currentProcess.value.processflowTypeDescrnTIme,
        processflowTypeAddres: 'F002', // 若无该字段，留空
        processflowTypeState: currentProcess.value.processflowTypeState, // 从表格行获取的状态
        processflowTypeNumber: '100', // 完工数量总和（字符串）
        // 关键：将报工明细数组转为 JSON 字符串（若后端要求字符串）
        processflowTypeNumberDescription: reportItems.value[0]?.qualified.toString() || '',
        // 单个部门/人员（取第一个报工项，若允许多个需调整）
        processflowTypeBumian: reportItems.value[0]?.department || '',
        personnel: reportItems.value[0]?.people || '',
        personnelDescription: totalQuantity // 报工数量总和（字符串）
    }
    console.log(fromsw)
    axios.put("https://localhost:7207/api/Production/ProcessflowUpdate", fromsw).then((res => {
        if (res.data.code == 212) {
            ElMessage.success('修改成功');
            isReportDialogVisible.value = false;
        }
        else {
            ElMessage.info('修改失败');
        }
    }))

};

// 导出工序
const exportProcess = () => {
    console.log('导出工序流程');
    ElMessage.success('导出成功');
};

// 获取工序数据
const FookShow = () => {
    axios.get("https://localhost:7006/api/Process/ProductionworkorderQuser")
        .then(res => {
            if (res.data && res.data.data) {
                processList.value = res.data.data;
            }
        })
        .catch(error => {
            console.error('获取工序数据失败:', error);
            ElMessage.error('获取工序数据失败，请检查网络连接');
        });
};

// 关闭对话框确认
const handleReportClose = (done) => {
    ElMessageBox.confirm('确定关闭报工对话框吗？', '提示', {
        confirmButtonText: '关闭',
        cancelButtonText: '取消',
        type: 'question'
    })
        .then(() => done())
        .catch(() => { });
};

// 添加报工项
const addReportItem = () => {
    reportItems.value.push({
        department: '',
        people: '',
        quantity: 0,
        qualified: 0,
        unqualified: 0,
        remark: ''
    });
};

// 处理选择变化
const handleSelectionChange = (selection) => {
    multipleSelection.value = selection;
};

// 移除选中项
const removeSelectedItems = () => {
    if (multipleSelection.value.length === 0) {
        ElMessage.warning('请先选择要移除的项目');
        return;
    }

    ElMessageBox.confirm(
        `确定要移除选中的 ${multipleSelection.value.length} 个项目吗？`,
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }
    )
        .then(() => {
            const selectedIndices = multipleSelection.value.map(
                item => reportItems.value.indexOf(item)
            );
            selectedIndices.sort((a, b) => b - a).forEach(index => {
                if (index > -1) {
                    reportItems.value.splice(index, 1);
                }
            });
            multipleSelection.value = [];
            ElMessage.success('移除成功');
        })
        .catch(() => { });
};

// 更新不合格数量
const updateUnqualified = (row) => {
    const quantity = parseInt(row.quantity) || 0;
    const qualified = parseInt(row.qualified) || 0;

    if (qualified > quantity) {
        row.qualified = quantity;
        ElMessage.warning('合格数量不能大于生产数量');
    }

    row.unqualified = quantity - qualified;
};

// 新增基础信息和生产物品数据
const baseInfo = ref({});
const productInfo = ref({});

const Mookds = () => {
    axios.get(`https://localhost:7006/api/Process/ProductionworkorderDan?ProductionworkorderNameId=${id}`)
        .then(res => {
            if (res.data && res.data.data.length > 0) {
                const data = res.data.data[0];

                // 基础信息映射
                baseInfo.value = {
                    productionworkorderId: data.productionworkorderId,
                    productionworkorderDate: data.productionworkorderDate,
                    productionworkorderNameId: data.productionworkorderDId,
                    productionworkorderStatus: data.productionworkorderStatus,
                    productionworkorderDescription: data.productionworkorderDescription,
                    productionworkorderName: data.productionworkorderName,
                    productionworkorderHId: data.productionworkorderHId,
                    productionworkorderTypeName: data.productionworkorderTypeName,
                    productionworkorderWId: data.productionworkorderWId
                };

                // 生产物品映射
                productInfo.value = {
                    productionworkorderTitle: data.productionworkorderTitle,
                    productionworkorderType: data.productionworkorderType,
                    productionworkorderGender: data.productionworkorderGender,
                    productionworkorderNumber: data.productionworkorderNumber,
                    productionworkorderJDorker: data.productionworkorderJDorker,
                    productionworkorderHand: data.productionworkorderHand,
                    productionworkorderDorker: data.productionworkorderDorker,
                    productionworkorderNDorker: data.productionworkorderNDorker
                };
            }
        })
        .catch(error => {
            console.error('获取工单详情失败:', error);
            ElMessage.error('获取工单详情失败，请检查网络连接');
        });
};
// 初始化
onMounted(() => {
    FookShow();
    Mookds();
});
</script>

<style scoped>
.work-order {
    padding: 20px;
    font-size: 14px;
}

.header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
}

.info span {
    margin-right: 20px;
    color: #666;
}

.actions ElButton {
    margin-right: 10px;
}

.section {
    margin-bottom: 30px;
    border: 1px solid #eee;
    padding: 15px;
    border-radius: 4px;
}

h3 {
    margin-bottom: 15px;
    color: #333;
    border-bottom: 1px solid #eee;
    padding-bottom: 10px;
}

.row {
    display: flex;
}

.col {
    width: 50%;
    padding-right: 20px;
}

p {
    margin-bottom: 10px;
    color: #666;
}

.attachment-list {
    display: flex;
    gap: 20px;
}

.attachment-item {
    border: 1px solid #eee;
    padding: 15px;
    border-radius: 4px;
    flex: 1;
}

.action-link {
    color: #409eff;
    cursor: pointer;
    margin-right: 10px;
}

.action-divider {
    color: #ccc;
    margin-right: 10px;
}

.report-form {
    padding: 15px;
}

.form-header {
    margin-bottom: 15px;
    padding: 10px;
    border: 1px solid #eee;
    border-radius: 4px;
    background-color: #f9fafc;
}

.form-row {
    display: flex;
    margin-bottom: 10px;
}

.form-col {
    flex: 1;
    margin-right: 20px;
}

.form-label {
    color: #909399;
    margin-right: 5px;
}

.form-value {
    color: #303133;
}

.form-actions {
    margin-bottom: 15px;
}
</style>